import axios from 'axios'
import { Toast } from 'vant'
import {getToken} from '../utils/auth'
// 局部使用 
const instance = axios.create({
    baseURL:  import.meta.env.VITE_HOST,
    timeout: 10000,
    headers: {
        'X-Custom-Header': 'foobar',
        'Content-Type': 'application/json;charset=utf-8',
    }
});



//请求拦截
instance.interceptors.request.use(async (config) => {
    Toast.loading({
        message: '加载中...',
        type: "loading",
    });
    config.headers = config.headers || {};
    config.headers.authorization = 'Bearer ' + getToken()
    return config;
}, (error) => {
    Toast.clear()
    console.log(error)
    Toast(error);
});

//返回值拦截
instance.interceptors.response.use(async (response) => {
    Toast.clear();
    const res = response.data;
    if (res.code == 200) {
        return res;
    }
    else {
        Toast(res.message || "服务器响应出错");
        return res;
    }
}, error => {
    Toast.clear()
    console.log(error)
    Toast(error);
});

export interface requestParam {
    url: string
    data?: any,
}

//post 请求封装

export const post = (config: requestParam) => {
    return instance({
        ...config,
        method: "post",
        data: config.data,
    })
}
//put 请求封装
export const put = (config: requestParam) => {
    return instance({
        ...config,
        method: "put",
        data: JSON.stringify(config.data),
    })
}
//get 请求封装
export const get = (config: requestParam) => {
    return instance({
        ...config,
        method: "get",
        params: config.data,
    })
}

//delete 请求封装
export const del = (config: requestParam) => {
    return instance({
        ...config,
        method: "delete",
    })
}

export default instance;